package com.skeeey.aim.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.tools.zip.ZipOutputStream;

import static com.skeeey.aim.util.AIMUtil.*;

public class ZipDir {
	public static void zip(String inputDir, String outFileName) {
		String zipFileName = getSystemConfig("zip.temp.path") + File.separator + outFileName + ".zip";
		zip(zipFileName, new File(inputDir));
	}

	private static void zip(String zipFileName, File inputDir) {
		ZipOutputStream out = null;
		try {
			out = new ZipOutputStream(new FileOutputStream(zipFileName));
			out.setEncoding("UTF-8");
			zip(out, inputDir, "");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// do nothing
				}
			}
		}
	}

	private static void zip(ZipOutputStream out, File inputDir, String base) {
		FileInputStream in = null;
		try {
			if (inputDir.isDirectory()) {
				File[] files = inputDir.listFiles();
				base = base.length() == 0 ? "" : base + File.separator;
				for (int i = 0; i < files.length; i++) {
					String fileName = base + files[i].getName();
					if(files[i].isDirectory() && !fileName.contains("证明材料")) {
						fileName = fileName + "(" + getFileCounts(files[i]) + ")";
					}
					
					zip(out, files[i], fileName);
				}
			} else {
				out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
				in = new FileInputStream(inputDir);
				byte[] buffer = new byte[10 * 1024];
				int b = -1;
				while ((b = in.read(buffer)) != -1) {
					out.write(buffer, 0, b);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// do nothing
				}
			}
		}
	}
	
	private static int getFileCounts(File file) {
		int i = 0;
		if(file.isDirectory()) {
			for(File sub : file.listFiles()) {
				if(sub.isDirectory()) {
					i = i + sub.listFiles().length;
				} else {
					i = file.listFiles().length;
					break;
				}
			}
		}
		return i;
	}

	public static void main(String[] temp) {
		zip("/mnt/myprojects/aim/data-storage/华北/河北/保定市/保定聚合/2013-03-12/", "test");
	}
}
